Popular Searches
Popular Course Categories
Popular Courses

Selenium + API Testing

Selenium + API Testing

API & Database Integration

Selenium + API Testing

Selenium + API Testing means combining browser-based UI automation with API-level testing in the same automation framework. Selenium WebDriver is used to automate web applications through the browser, while API testing tools such as REST Assured are used to send HTTP requests and validate API responses.

This combination is especially useful for end-to-end testing because APIs can be used to prepare test data, validate backend responses, create or delete records, and verify application behavior before or after performing UI actions. A hybrid UI + API framework can therefore test both the user interface and the underlying services.

In a Java automation framework, Selenium WebDriver, REST Assured, TestNG, Maven, and supporting utilities can work together to create a reusable UI and API automation architecture.

Course Resource: Selenium Training | Register for Course Demo


1. What is API Testing?

API Testing is the process of validating application programming interfaces to verify that they work correctly, return expected responses, enforce required rules, and handle valid and invalid requests properly.

Unlike UI testing, API testing does not require interacting with the application's graphical interface. Tests communicate directly with API endpoints using HTTP methods such as GET, POST, PUT, PATCH, and DELETE.

API testing commonly validates:

  • HTTP status codes.
  • Response body.
  • Response headers.
  • Response time.
  • JSON or XML response structure.
  • Authentication and authorization.
  • Request parameters.
  • Request payloads.
  • Business rules.
  • Error handling.


2. What is Selenium?

Selenium is an open-source framework used to automate web browsers. Selenium WebDriver allows automation scripts to interact with web elements such as text fields, buttons, links, dropdowns, tables, and forms.

Selenium is primarily used for UI automation rather than directly testing REST APIs.

Java Test

    |

    v

Selenium WebDriver

    |

    v

Browser

    |

    v

Web Application


3. What is REST API?

REST, or Representational State Transfer, is an architectural style commonly used for building web APIs. REST APIs generally use HTTP methods to perform operations on resources.

HTTP MethodTypical PurposeExample
GETRetrieve dataGet user details
POSTCreate dataCreate a user
PUTReplace/update dataUpdate a user
PATCHPartially update dataUpdate user email
DELETEDelete dataDelete a user


4. Why Combine Selenium and API Testing?

Selenium and API testing solve different testing problems. Selenium validates what users see and interact with, while API testing validates communication between application components and backend services.

Combining them allows a framework to validate an end-to-end business flow at multiple layers.

  • Use API calls to create test data.
  • Use Selenium to perform UI actions.
  • Use APIs to validate backend results.
  • Use APIs to clean up test data.
  • Reduce unnecessary UI setup steps.
  • Validate UI and backend behavior together.
  • Improve test coverage.
  • Build reusable end-to-end automation.


5. Selenium Testing vs API Testing

FeatureSelenium UI TestingAPI Testing
LayerPresentation/UI layerService/API layer
Browser RequiredUsually yesNo
SpeedGenerally slowerGenerally faster
Main ToolSelenium WebDriverREST Assured or similar API client
ValidationUI elements and user flowsStatus, headers, body, schema, business rules
Typical DataForm fields and UI valuesJSON/XML request and response
Best UseBrowser workflowsService/API validation


6. What is REST Assured?

REST Assured is a Java library designed to simplify testing and validating REST APIs. It provides a readable syntax for constructing HTTP requests and validating responses.

REST Assured can be combined with TestNG to create structured API automation suites. A common BDD-style flow is:

given()

    |

    v

Request Configuration

    |

    v

when()

    |

    v

HTTP Request

    |

    v

then()

    |

    v

Response Validation


7. Selenium + API Testing Architecture

                    Automation Framework

                            |

              +-------------+-------------+

              |                           |

              v                           v

        UI Automation              API Automation

              |                           |

              v                           v

     Selenium WebDriver            REST Assured

              |                           |

              v                           v

          Browser                    API Server

              |                           |

              +-------------+-------------+

                            |

                            v

                      TestNG Assertions

                            |

                            v

                         Reports

Modern automation frameworks can keep UI and API tests in separate layers while sharing common configuration, test data, utilities, logging, reporting, and execution infrastructure.


8. Maven Dependencies

A Java Maven project can include Selenium, REST Assured, and TestNG dependencies. Version numbers should be selected according to the project's compatibility and dependency-management strategy.

<dependencies>

    <dependency>

        <groupId>org.seleniumhq.selenium</groupId>

        <artifactId>selenium-java</artifactId>

        <version>YOUR_SELENIUM_VERSION</version>

    </dependency>

 

    <dependency>

        <groupId>io.rest-assured</groupId>

        <artifactId>rest-assured</artifactId>

        <version>YOUR_REST_ASSURED_VERSION</version>

        <scope>test</scope>

    </dependency>

 

    <dependency>

        <groupId>org.testng</groupId>

        <artifactId>testng</artifactId>

        <version>YOUR_TESTNG_VERSION</version>

        <scope>test</scope>

    </dependency>

</dependencies>


9. Basic API GET Request

A GET request is commonly used to retrieve information from an API.

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

 

import org.testng.annotations.Test;

 

public class ApiGetTest {

 

    @Test

    public void getUserTest() {

        given()

        .when()

            .get("https://example.com/api/users/1")

        .then()

            .statusCode(200);

    }

}

The test sends a GET request and verifies that the server returns the expected HTTP status code.


10. Validating API Response Body

API testing should not stop at status-code validation. The response body should also be checked when appropriate.

given()

.when()

    .get("https://example.com/api/users/1")

.then()

    .statusCode(200)

    .body("id", equalTo(1));

This verifies both the response status and a value in the response body.


11. Capturing API Response

A response can be stored in a REST Assured Response object for further validation or for passing data to subsequent operations.

import io.restassured.response.Response;

import static io.restassured.RestAssured.*;

 

Response response =

    given()

    .when()

        .get("https://example.com/api/users/1");

 

System.out.println(response.getStatusCode());

System.out.println(response.asPrettyString());


12. API POST Request

A POST request is generally used to create a new resource.

String requestBody = """

{

    "name": "John",

    "job": "Tester"

}

""";

 

given()

    .contentType("application/json")

    .body(requestBody)

.when()

    .post("https://example.com/api/users")

.then()

    .statusCode(201);

The exact status code depends on the API contract. A successful resource-creation operation commonly returns 201 Created, but the API documentation should be treated as the source of truth.


13. API PUT Request

PUT is commonly used to replace or update an existing resource.

String requestBody = """

{

    "name": "John Updated",

    "job": "Senior Tester"

}

""";

 

given()

    .contentType("application/json")

    .body(requestBody)

.when()

    .put("https://example.com/api/users/1")

.then()

    .statusCode(200);


14. API PATCH Request

PATCH is commonly used when only part of a resource needs to be updated.

String requestBody = """

{

    "job": "Automation Engineer"

}

""";

 

given()

    .contentType("application/json")

    .body(requestBody)

.when()

    .patch("https://example.com/api/users/1")

.then()

    .statusCode(200);


15. API DELETE Request

DELETE is used to remove a resource when the API supports deletion.

given()

.when()

    .delete("https://example.com/api/users/1")

.then()

    .statusCode(204);

The expected status code depends on the API contract. Some APIs return 200, 202, or 204 after a successful deletion.


16. API Headers

HTTP headers provide additional information about a request or response. Common API headers include Content-Type, Accept, and authorization-related headers.

given()

    .header("Accept", "application/json")

.when()

    .get("https://example.com/api/users")

.then()

    .statusCode(200);


17. Content-Type Header

The Content-Type header indicates the format of the request body being sent to the server.

given()

    .contentType("application/json")

    .body("{\"name\":\"John\"}")

.when()

    .post("https://example.com/api/users")

.then()

    .statusCode(201);


18. Query Parameters

Query parameters are commonly used to filter, search, sort, or control API responses.

given()

    .queryParam("page", 2)

    .queryParam("limit", 10)

.when()

    .get("https://example.com/api/users")

.then()

    .statusCode(200);

The resulting request conceptually contains parameters such as ?page=2&limit=10.


19. Path Parameters

Path parameters identify a specific resource within the URL path.

given()

    .pathParam("id", 10)

.when()

    .get("https://example.com/api/users/{id}")

.then()

    .statusCode(200);


20. Authentication in API Testing

Many APIs require authentication. Common mechanisms include API keys, Basic Authentication, Bearer tokens, OAuth-based authentication, and session-based authentication.

A bearer token can be supplied using an Authorization header.

String token = "YOUR_TOKEN";

 

given()

    .header("Authorization", "Bearer " + token)

.when()

    .get("https://example.com/api/profile")

.then()

    .statusCode(200);

Sensitive tokens should be supplied through secure configuration or secret-management mechanisms rather than committed as plain text in source code.


21. JSON Response Validation

JSON is commonly used for REST API request and response bodies. REST Assured provides mechanisms for validating JSON fields.

given()

.when()

    .get("https://example.com/api/users/1")

.then()

    .statusCode(200)

    .body("name", equalTo("John"))

    .body("active", equalTo(true));


22. Extracting JSON Values

API response values can be extracted and used in later steps.

String userId =

    given()

    .when()

        .get("https://example.com/api/users/1")

    .then()

        .statusCode(200)

        .extract()

        .path("id");

 

System.out.println("User ID: " + userId);


23. API Chaining

API chaining means using data returned by one API request in another API request.

For example:

Create User API

      |

      v

Capture User ID

      |

      v

Get User API

      |

      v

Update User API

      |

      v

Delete User API

This approach is useful for end-to-end service workflows where one operation depends on the output of another.


24. Creating and Reusing an API ID

int userId =

    given()

        .contentType("application/json")

        .body("{\"name\":\"John\"}")

    .when()

        .post("https://example.com/api/users")

    .then()

        .statusCode(201)

        .extract()

        .path("id");

 

System.out.println("Created User ID: " + userId);


25. API Testing with TestNG

TestNG can be used as the test execution framework for REST Assured tests.

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

 

import org.testng.annotations.Test;

 

public class UserApiTest {

 

    @Test

    public void verifyUser() {

        given()

        .when()

            .get("https://example.com/api/users/1")

        .then()

            .statusCode(200)

            .body("id", equalTo(1));

    }

}

TestNG provides annotations, assertions, groups, dependencies, Data Providers, listeners, suite execution, and other features useful for organizing API automation.


26. Selenium + API End-to-End Flow

A hybrid test can use an API to prepare data and Selenium to validate the corresponding UI behavior.

API: Create Test User

        |

        v

Capture User ID

        |

        v

Open Application with Selenium

        |

        v

Login Through UI

        |

        v

Navigate to User Profile

        |

        v

Validate UI Information

        |

        v

API: Verify Backend Data

        |

        v

API: Delete Test User


27. API for Test Data Creation

Creating test data through the UI can be time-consuming. If the application provides suitable APIs, an API call can create the required test data before the UI test starts.

API

 |

 +-- Create Customer

 |

 +-- Create Product

 |

 +-- Create Order

 |

 v

Selenium UI Test

This can reduce the number of UI steps required for test setup while keeping the actual user workflow under UI validation.


28. Selenium Login with API-Based Test Data

Suppose a test needs a new user account. Instead of navigating through the registration UI every time, an API can create the account first, and Selenium can then validate the login workflow.

API

 |

 v

Create User

 |

 v

User Credentials

 |

 v

Selenium Login Page

 |

 v

Enter Credentials

 |

 v

Click Login

 |

 v

Validate Dashboard


29. Selenium UI Validation After API Operation

An API can create or update a resource, after which Selenium can open the corresponding UI page and verify that the change is displayed correctly.

API Update

    |

    v

Backend Data Changed

    |

    v

Open Web Application

    |

    v

Navigate to Resource

    |

    v

Validate UI

    |

    v

Compare Expected vs Actual


30. API Validation After Selenium Operation

The reverse approach is also useful. Selenium can perform a user action and the API can then verify that the expected backend change occurred.

Selenium UI

    |

    v

User Creates Order

    |

    v

Application Processes Request

    |

    v

API GET Order

    |

    v

Validate Order Status

    |

    v

Test Result


31. Complete Hybrid Example

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class HybridUiApiTest {

 

    private WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

    }

 

    @Test

    public void verifyUserThroughUiAndApi() {

 

        given()

        .when()

            .get("https://example.com/api/users/1")

        .then()

            .statusCode(200)

            .body("id", equalTo(1));

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.id("username"))

                .sendKeys("testUser");

 

        driver.findElement(By.id("password"))

                .sendKeys("testPassword");

 

        driver.findElement(By.id("loginButton"))

                .click();

 

        System.out.println("UI validation completed.");

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}

This is a simplified example. In a production framework, UI actions, API clients, configuration, test data, assertions, and reporting should generally be separated into reusable components.


32. API Utility Class

Instead of writing REST Assured request logic repeatedly, common API operations can be moved into reusable utility or client classes.

public class ApiClient {

 

    public static Response get(String endpoint) {

        return given()

                .when()

                .get(endpoint);

    }

 

    public static Response post(String endpoint, String body) {

        return given()

                .contentType("application/json")

                .body(body)

                .when()

                .post(endpoint);

    }

 

    public static Response delete(String endpoint) {

        return given()

                .when()

                .delete(endpoint);

    }

}

Reusable API clients help keep test classes focused on test scenarios instead of low-level request construction.


33. Base API Configuration

Common API configuration such as the base URI can be centralized.

import io.restassured.RestAssured;

 

public class ApiConfig {

 

    public static void setup() {

        RestAssured.baseURI = "https://example.com";

    }

}

A more scalable framework can load the base URI from environment-specific configuration rather than hard-coding it.


34. API Specifications

REST Assured supports reusable request and response specifications. These can centralize common headers, base paths, content types, and validation rules.

RequestSpecification requestSpec =

    new RequestSpecBuilder()

        .setBaseUri("https://example.com")

        .setContentType("application/json")

        .build();

Reusable specifications reduce duplication across API test classes.


35. API Response Specifications

ResponseSpecification responseSpec =

    new ResponseSpecBuilder()

        .expectContentType("application/json")

        .build();

Response specifications can be used when multiple tests share common response expectations.


36. Request Body Using JSON

API requests often require JSON payloads.

String body = """

{

    "username": "john",

    "email": "[email protected]",

    "role": "customer"

}

""";

 

given()

    .contentType("application/json")

    .body(body)

.when()

    .post("https://example.com/api/users")

.then()

    .statusCode(201);


37. API Negative Testing

API automation should also verify how an API behaves when invalid input is provided.

Examples include:

  • Invalid authentication token.
  • Missing required fields.
  • Invalid resource ID.
  • Unsupported HTTP method.
  • Malformed request body.
  • Invalid query parameter.
  • Unauthorized user.
  • Duplicate resource creation.

given()

    .header("Authorization", "Bearer invalid-token")

.when()

    .get("https://example.com/api/profile")

.then()

    .statusCode(401);


38. API Status Code Validation

Status CodeMeaningTypical Testing Purpose
200OKSuccessful request
201CreatedSuccessful resource creation
202AcceptedRequest accepted for processing
204No ContentSuccessful operation without response body
400Bad RequestInvalid request data
401UnauthorizedAuthentication failure/missing credentials
403ForbiddenInsufficient permissions
404Not FoundResource does not exist
500Internal Server ErrorServer-side failure

The expected status code should always be determined from the API contract and application behavior.


39. API Response Time Validation

Response time can be measured as part of functional API checks, although dedicated performance testing requires more specialized approaches.

given()

.when()

    .get("https://example.com/api/users")

.then()

    .statusCode(200)

    .time(lessThan(3000L));

The threshold should be based on the application's agreed requirements rather than an arbitrary value.


40. Authentication Token Extraction

A login API may return an authentication token that can be used by subsequent API requests.

String token =

    given()

        .contentType("application/json")

        .body("""

        {

            "username": "testUser",

            "password": "testPassword"

        }

        """)

    .when()

        .post("https://example.com/api/login")

    .then()

        .statusCode(200)

        .extract()

        .path("token");

 

System.out.println("Token received.");

Do not print real authentication tokens in production logs or reports.


41. Using API Token with Selenium Test

An API token can sometimes be used to prepare or authenticate backend operations before a UI test. The exact mechanism depends on the application architecture.

Login API

    |

    v

Authentication Token

    |

    v

Create Required Test Data

    |

    v

Selenium UI Test

    |

    v

Validate User Workflow


42. API Data Cleanup

One of the practical benefits of API integration is fast test-data cleanup.

Test Execution

      |

      v

Create Test Data

      |

      v

Run UI Test

      |

      v

Validate Result

      |

      v

Delete Test Data Through API

      |

      v

Clean Environment

This approach can help keep test environments cleaner when the application's APIs provide appropriate operations for test data management.


43. Selenium + API Testing with DataProvider

TestNG Data Providers can supply multiple combinations of UI and API test data.

@DataProvider(name = "users")

public Object[][] users() {

    return new Object[][] {

        {"user1", "pass1"},

        {"user2", "pass2"},

        {"user3", "pass3"}

    };

}

 

@Test(dataProvider = "users")

public void hybridTest(String username, String password) {

 

    System.out.println(

        "Testing user: " + username

    );

 

    // API setup and Selenium UI validation

}

This allows the same hybrid workflow to execute against multiple test-data combinations.


44. Selenium + API Testing with Page Object Model

The Page Object Model can be combined with API client classes. Page classes manage UI interactions while API classes manage service interactions.

Test Class

    |

    +-- LoginPage

    |      |

    |      +-- Selenium UI actions

    |

    +-- UserApiClient

           |

           +-- REST API actions

This separation improves maintainability and makes the framework easier to extend.


45. Hybrid Framework Folder Structure

src

|-- main

|   |-- java

|       |-- pages

|       |   |-- LoginPage.java

|       |   |-- DashboardPage.java

|       |

|       |-- api

|       |   |-- UserApiClient.java

|       |   |-- AuthApiClient.java

|       |

|       |-- utilities

|           |-- DriverFactory.java

|           |-- ConfigReader.java

|           |-- ApiUtils.java

|

|-- test

    |-- java

        |-- tests

        |   |-- LoginTest.java

        |   |-- UserTest.java

        |   |-- HybridTest.java

        |

        |-- data

            |-- TestDataProvider.java


46. Separation of UI and API Responsibilities

ComponentResponsibility
Page ClassesWeb UI interaction
API ClientHTTP request and response handling
Data ProviderTest data
Driver FactoryWebDriver creation and management
Config ReaderEnvironment configuration
AssertionsExpected vs actual validation
ReportsTest execution results
Test ClassesBusiness-level test scenarios


47. UI Test Followed by API Validation

Consider an e-commerce checkout scenario.

Selenium

   |

   v

Login

   |

   v

Search Product

   |

   v

Add Product to Cart

   |

   v

Checkout

   |

   v

Place Order

   |

   v

API GET Order

   |

   v

Validate Order Status

   |

   v

Test Result

The UI validates the user workflow while the API validates the backend order information.


48. API Test Followed by UI Validation

The opposite workflow can also be implemented.

POST Product API

      |

      v

Product Created

      |

      v

Open Website

      |

      v

Search Product

      |

      v

Validate Product Details

      |

      v

Delete Product API


49. API and UI Assertions

Assertions should be placed at the appropriate testing layer.

API Assertions

 |

 +-- Status Code

 +-- Response Body

 +-- Headers

 +-- Schema

 +-- Business Rules

 

UI Assertions

 |

 +-- Page Title

 +-- Element Visibility

 +-- Text

 +-- URL

 +-- User Workflow Result


50. End-to-End Order Example

A realistic hybrid test could follow the following sequence:

  1. Create a customer through an API.
  2. Create or prepare a product through an API.
  3. Open the application using Selenium.
  4. Log in through the UI.
  5. Search for the product.
  6. Add the product to the cart.
  7. Complete checkout.
  8. Capture the order information.
  9. Use the API to retrieve the order.
  10. Validate the backend order status.
  11. Clean up test data through APIs where supported.


51. API Testing and Test Reports

Hybrid frameworks can report UI and API test results in a unified reporting system. Each test should provide enough information to identify whether the failure occurred during API preparation, UI execution, API validation, or cleanup.

Hybrid Test

   |

   +-- API Setup       PASS

   |

   +-- Selenium UI     PASS

   |

   +-- API Validation  PASS

   |

   +-- Cleanup         PASS

   |

   v

Test Report

Frameworks can integrate reporting tools such as Allure or Extent Reports to provide richer execution information. :contentReference[oaicite:0]{index=0}


52. API Logging

Logging is useful for debugging API failures, but sensitive information should be protected.

Useful information may include:

  • HTTP method.
  • Endpoint without sensitive query data.
  • Status code.
  • Response time.
  • Correlation or test ID.
  • Relevant validation result.

Passwords, access tokens, API keys, session cookies, and other secrets should be masked or excluded from logs.


53. Selenium + API Testing in CI/CD

Hybrid UI/API suites can be executed through Maven-based CI/CD pipelines.

Developer Commit

       |

       v

CI/CD Pipeline

       |

       v

Maven Build

       |

       +----------------+

       |                |

       v                v

   API Tests        UI Tests

       |                |

       v                v

 REST Assured      Selenium

       |                |

       +-------+--------+

               |

               v

          Test Results

               |

               v

             Report

Hybrid automation projects commonly use Maven and TestNG for execution and can integrate with CI systems such as Jenkins. :contentReference[oaicite:1]{index=1}


54. Maven Execution

A Maven project can execute the test suite using the Maven test lifecycle.

mvn clean test

Specific TestNG suite files can also be configured through Maven Surefire depending on the project setup.


55. API Testing with Environment Configuration

Different environments may have different API base URLs.

EnvironmentExample Base URL
Developmenthttps://dev.example.com
QAhttps://qa.example.com
Staginghttps://stage.example.com
Productionhttps://www.example.com

Actual environment URLs should be stored in configuration rather than scattered throughout test classes.


56. Configuration-Based Hybrid Testing

Environment Configuration

          |

          +-- UI Base URL

          |

          +-- API Base URL

          |

          +-- Browser

          |

          +-- Authentication

          |

          v

      Test Framework

          |

     +----+----+

     |         |

     v         v

  Selenium   REST Assured


57. Common Mistakes in Selenium + API Testing

  • Using Selenium for API testing instead of an API client.
  • Putting all UI and API logic into one large test class.
  • Hard-coding environment URLs.
  • Hard-coding API tokens and passwords.
  • Sharing WebDriver instances unsafely between parallel tests.
  • Ignoring API response validation.
  • Validating only HTTP status codes and not important response data.
  • Not cleaning up API-created test data.
  • Making UI tests dependent on unnecessary UI-based data setup.
  • Mixing framework utilities with business test logic.
  • Logging sensitive authentication information.
  • Creating tightly coupled API and UI components.


58. Best Practices for Selenium + API Testing

  • Keep UI and API responsibilities separated.
  • Create reusable API client classes.
  • Use Page Object Model for UI automation.
  • Centralize environment configuration.
  • Use Data Providers for repeated test data.
  • Use API calls for efficient test-data setup when appropriate.
  • Use APIs for cleanup when suitable endpoints are available.
  • Validate both API responses and UI behavior.
  • Use meaningful assertions.
  • Protect credentials and tokens.
  • Keep logs useful but safe.
  • Design WebDriver management for thread safety before enabling parallel execution.
  • Integrate the framework with Maven and CI/CD.
  • Generate unified and understandable test reports.


59. Selenium + API Testing vs UI-Only Testing

AspectUI-Only ApproachHybrid UI + API Approach
Test Data SetupOften through UICan use API where appropriate
Backend ValidationIndirectDirect API validation possible
Execution SpeedMore UI operationsCan reduce unnecessary UI setup
CoveragePrimarily UI behaviorUI and service layers
ArchitecturePrimarily page objectsPage objects + API clients
Data CleanupMay require UICan use APIs where supported


60. Practical Project Structure

automation-framework/

|

|-- pom.xml

|-- testng.xml

|

|-- src/

|   |-- main/

|   |   |-- java/

|   |       |-- pages/

|   |       |   |-- LoginPage.java

|   |       |   |-- DashboardPage.java

|   |       |

|   |       |-- api/

|   |       |   |-- UserApiClient.java

|   |       |   |-- OrderApiClient.java

|   |       |

|   |       |-- utilities/

|   |           |-- DriverFactory.java

|   |           |-- ConfigReader.java

|   |           |-- ApiUtils.java

|   |

|   |-- test/

|       |-- java/

|           |-- tests/

|           |   |-- LoginTest.java

|           |   |-- OrderTest.java

|           |   |-- HybridOrderTest.java

|           |

|           |-- data/

|               |-- TestDataProvider.java

|

|-- resources/

|   |-- config.properties

|   |-- testdata.json


61. Complete Hybrid Testing Flow

TestNG

  |

  v

Test Data

  |

  +-----------------------+

  |                       |

  v                       v

API Setup              Selenium Setup

  |                       |

  v                       v

Create Data            Open Browser

  |                       |

  v                       v

Capture ID              Login

  |                       |

  +-----------+-----------+

              |

              v

         UI Workflow

              |

              v

        Business Action

              |

              v

        API Validation

              |

              v

          Assertions

              |

              v

           Cleanup

              |

              v

           Report


62. Real-World E-Commerce Example

Consider an e-commerce application with customer, product, cart, and order APIs.

API: Create Customer

        |

        v

API: Create Product

        |

        v

Selenium: Login

        |

        v

Selenium: Search Product

        |

        v

Selenium: Add to Cart

        |

        v

Selenium: Checkout

        |

        v

API: Get Order

        |

        v

Validate Order

        |

        v

API: Cleanup Data

This architecture allows the UI layer to focus on user-facing workflows while APIs support setup, validation, and cleanup.


63. API and UI Test Independence

Not every API test needs Selenium, and not every Selenium test needs an API call. The purpose of a hybrid framework is to use each layer where it provides meaningful coverage.

  • Use API-only tests for service behavior.
  • Use UI-only tests for visual and interaction behavior.
  • Use hybrid tests for important end-to-end business workflows.


64. When Should You Use Selenium?

  • When browser behavior must be validated.
  • When user interaction is important.
  • When web elements and workflows need verification.
  • When navigation and UI state need validation.
  • When browser compatibility must be tested.


65. When Should You Use API Testing?

  • When backend services need direct validation.
  • When UI is not required for the scenario.
  • When large amounts of test data need to be prepared efficiently.
  • When response status, body, headers, or business rules need validation.
  • When service-level regression tests are required.


66. When Should You Use Hybrid Testing?

  • When an end-to-end business flow spans UI and backend services.
  • When API data can efficiently prepare UI test scenarios.
  • When UI actions need backend verification.
  • When API cleanup can simplify test environment management.
  • When both user-facing and service-level behavior are important.


67. Advantages of Selenium + API Testing

  • Broader Coverage: Both UI and API layers can be tested.
  • Faster Data Setup: APIs can prepare data without performing long UI workflows.
  • Backend Validation: UI actions can be verified through API responses.
  • Better Reusability: API clients and Page Objects can be reused.
  • Improved Maintainability: Responsibilities can be separated into framework components.
  • Efficient End-to-End Testing: API and UI layers can work together for business workflows.
  • CI/CD Integration: UI and API suites can be executed as part of automated pipelines.


68. Limitations and Challenges

  • The framework becomes more complex than a UI-only framework.
  • Developers must understand both UI and API automation.
  • Authentication flows can require additional implementation.
  • API and UI environments must be compatible.
  • Test-data synchronization can become challenging.
  • Parallel execution requires careful resource management.
  • Additional reporting and logging design may be required.


69. Interview Questions on Selenium + API Testing

1. Can Selenium test REST APIs directly?

Selenium is designed primarily for browser automation. REST APIs are generally tested using API clients or libraries such as REST Assured.

2. Why combine Selenium with API testing?

The combination allows a framework to validate both user-facing browser workflows and backend service behavior.

3. What is REST Assured?

REST Assured is a Java library commonly used to automate and validate REST APIs.

4. Can REST Assured work with TestNG?

Yes. REST Assured tests can be organized and executed using TestNG.

5. Can an API create data for Selenium tests?

Yes. When suitable APIs are available, they can be used to create test data before Selenium executes the UI workflow.

6. Can Selenium results be validated through APIs?

Yes. A UI action can be followed by an API request that verifies the corresponding backend state.

7. What is API chaining?

API chaining means using output from one API request as input to another API request.

8. Why use APIs for test-data cleanup?

API-based cleanup can be faster and less dependent on UI workflows when appropriate delete or reset endpoints are available.

9. What HTTP methods are commonly tested?

GET, POST, PUT, PATCH, and DELETE are commonly tested in REST API automation.

10. What should be validated in an API response?

Depending on the API contract, validation may include status code, response body, headers, schema, business rules, and response time.

11. How can API authentication be handled?

Authentication may involve API keys, Basic Authentication, bearer tokens, OAuth-based mechanisms, or other application-specific approaches.

12. How can API and UI test data be shared?

Data can be passed through test utilities, Data Providers, context objects, configuration objects, or dedicated test-data classes.

13. What is a hybrid automation framework?

A hybrid automation framework combines multiple automation layers or techniques, such as Selenium UI automation and REST API automation, under a common framework architecture.

14. Can Selenium and REST Assured use the same TestNG suite?

Yes. UI and API test classes can be organized in the same TestNG project and suite configuration.

15. What is the benefit of API setup before UI testing?

It can reduce unnecessary UI setup steps and allow tests to start with the required backend state.

16. What is the role of Page Object Model in hybrid automation?

POM separates Selenium page interactions from test logic, while API client classes can separately manage API operations.

17. Should every API test include Selenium?

No. API tests can run independently when browser behavior is not relevant.

18. Should every Selenium test include an API call?

No. API calls should be used when they provide useful setup, validation, cleanup, or business-flow coverage.

19. How can hybrid tests run in CI/CD?

Maven and TestNG can execute UI and API test suites in CI/CD pipelines, with reports generated after execution.

20. What is the main goal of Selenium + API automation?

The goal is to efficiently validate complete application behavior by testing appropriate UI and service-level scenarios through a maintainable automation framework.


70. Quick Reference Table

ConceptDescription
SeleniumBrowser automation framework
WebDriverAPI for controlling browsers
REST AssuredJava library for REST API automation
GETRetrieve a resource
POSTCreate a resource
PUTReplace/update a resource
PATCHPartially update a resource
DELETEDelete a resource
TestNGTest execution and organization framework
DataProviderSupplies multiple test-data sets
API ChainingUses output from one API in another API
API SetupCreates or prepares test data
API ValidationVerifies backend state after UI actions
POMSeparates UI page interaction logic
MavenBuild and dependency management


71. Learning Roadmap for Selenium + API Testing

  1. Learn Java fundamentals.
  2. Learn Selenium WebDriver basics.
  3. Learn locators and browser automation.
  4. Learn TestNG annotations and assertions.
  5. Understand HTTP and REST API fundamentals.
  6. Learn GET, POST, PUT, PATCH, and DELETE.
  7. Learn REST Assured.
  8. Learn API request and response validation.
  9. Learn authentication and authorization concepts.
  10. Learn JSON parsing and response extraction.
  11. Learn API chaining.
  12. Learn TestNG Data Providers.
  13. Learn Page Object Model.
  14. Create reusable API client classes.
  15. Combine API setup with Selenium tests.
  16. Validate UI actions through APIs.
  17. Add reporting and logging.
  18. Integrate Maven.
  19. Integrate CI/CD.
  20. Build a complete hybrid UI + API automation framework.


72. Practical Exercises

  1. Create a REST Assured GET test and validate the status code.
  2. Create a POST request with a JSON body.
  3. Validate a JSON response field.
  4. Extract an ID from an API response.
  5. Use the extracted ID in another API request.
  6. Create a Selenium login test.
  7. Create test data through an API and use it in Selenium.
  8. Perform a UI action and verify its result through an API.
  9. Create reusable API client methods.
  10. Combine Selenium, REST Assured, and TestNG.
  11. Use a Data Provider for multiple API/UI test scenarios.
  12. Add API and UI tests to a Maven project.
  13. Generate a combined automation report.
  14. Execute the hybrid suite through a CI/CD pipeline.


73. Final Hybrid Automation Architecture

                    TestNG Test Suite

                           |

             +-------------+-------------+

             |                           |

             v                           v

        API Test Layer               UI Test Layer

             |                           |

             v                           v

       REST Assured                Selenium WebDriver

             |                           |

             v                           v

        API Services                 Browser

             |                           |

             +-------------+-------------+

                           |

                           v

                    Shared Utilities

                           |

          +----------------+----------------+

          |                |                |

          v                v                v

       Config           Test Data       Reporting

          |                |                |

          +----------------+----------------+

                           |

                           v

                         Maven

                           |

                           v

                         CI/CD


74. Summary

Selenium + API Testing combines browser automation with direct service-level validation. Selenium WebDriver is responsible for testing web application behavior through the browser, while REST Assured can be used to automate REST API requests and validate their responses.

A hybrid framework can use APIs to prepare test data, Selenium to execute user workflows, and APIs again to validate backend results or clean up data. This approach can reduce unnecessary UI operations and provide broader coverage across application layers.

TestNG can coordinate both API and UI tests, while Data Providers can supply multiple test scenarios. Page Object Model can organize Selenium interactions, API client classes can encapsulate service operations, and Maven can manage dependencies and execution.

For larger projects, configuration management, secure credentials, reusable utilities, logging, reporting, parallel execution, and CI/CD integration should be designed as separate framework concerns.


75. Course Resources

Learn more about Selenium automation and related testing concepts:

Final Takeaway: Selenium and API testing complement each other. Selenium validates the application from the user's perspective, while API automation validates service behavior directly. When combined with TestNG, Page Object Model, Data Providers, reusable API clients, Maven, reporting, and CI/CD, they can form a structured hybrid automation framework for end-to-end testing.

whatsapp